<template>
  <div class="mod-monitor">
    <v-stage :config="stageConfig">
      <v-layer>
        <v-group>
          <!-- 绘制机台 -->
          <v-rect v-for="(machine, index) in machines" :key="'machine-' + index" :config="machine.config"
            @click="handleMachineClick(machine)" @dblclick="handleDbClick(machine)" @mouseenter="handleEnter(machine)"/>

          <v-text v-for="(machine, index) in machines" :key="'name-' + index" :config="{
            x: machine.config.x + 15,
            y: machine.config.y + 10,
            text: machine.ITEM_NAME,
            fontSize: 22,
            fill: '#1E90FF'
          }" />
        </v-group>


        <!-- 绘制连接线 -->
        <v-line v-for="(line, index) in lines" :key="'line-' + index" :config="line.config" />

        <!-- 悬浮提示框 -->
        <!-- <v-text :config="textConfig" /> -->
        <v-text v-for="(text, index) in texts" :key="'text-' + index" :config="text.config" />
      </v-layer>
    </v-stage>
    <!-- 弹窗, 新增 / 修改 -->
    <Monitor ref="monitorRef"></Monitor>
  </div>
</template>

<script>
import jsonData from "@/assets/json/data.json"
import Monitor from './monitor'
export default {
  data() {
    return {
      webSocket: null,
      wsUrl: 'ws://10.70.92.201:8088/wcs-admin/monitor',
      stageConfig: { width: 1100, height: 600 },
      // 机台数据
      machines: jsonData.machines,
      // 连接线数据
      lines: jsonData.lines,
      texts: jsonData.texts,
      // 悬浮提示框相关数据
      hoveredMachine: null, // 当前悬浮的机台
      // 全局数据（从后端获取并暂存的）
      globeScript: []
    }
  },
  components: {
    Monitor
  },
  mounted() {
    this.setUpWebSocket();
  },
  methods: {
    setUpWebSocket() {
      this.webSocket = new WebSocket(this.wsUrl); this.webSocket.onopen = e => {
        console.log("连接打开", this.webSocket.readyState);

        // this.webSocket.send("hello");
      };
      this.webSocket.onclose = e => {
        console.log(`连接关闭: code=${e.code}, reason=${e.reason}`)
      };
      // 收到消息
      this.webSocket.onmessage = e => {
        // console.log(`收到消息：${e.data}`);
        let jsonList = JSON.parse(e.data);
        //对数据进行处理
        this.globeScript = jsonList;
        // 将数据填充到各个机台
        this.fillMachineInfo();
      };
      // 异常
      this.webSocket.onerror = e => {
        console.log("连接异常!causyBy:", e)
      };
    },
    callback() {
      console.log("被调用了")
    },
    fillMachineInfo() {
      // 填充机台内容,内外卡控、资料信息
      for (let i = 0; i < this.machines.length; i++) {
        const machineScript = this.globeScript.filter(item => item.itemCode == this.machines[i].ITEM_CODE);
        // 填充内容
        for (let j = 0; j < machineScript.length; j++) {
          const singleScript = machineScript[j];
          if ("AGV_W" == singleScript.itemGrp) {
            this.machines[i].AGV_W.value = singleScript.itemValue;
            this.machines[i].AGV_W.oldVlue = singleScript.oldValue;
            this.machines[i].AGV_W.updateDate = this.timestampToTime(singleScript.updateDate);
          } else if ("AGV_N" == singleScript.itemGrp) {
            this.machines[i].AGV_N.value = singleScript.itemValue;
            this.machines[i].AGV_N.oldVlue = singleScript.oldValue;
            this.machines[i].AGV_N.updateDate = this.timestampToTime(singleScript.updateDate);
          } else if ("PLC_W" == singleScript.itemGrp) {
            this.machines[i].PLC_W.value = singleScript.itemValue;
            this.machines[i].PLC_W.oldVlue = singleScript.oldValue;
            this.machines[i].PLC_W.updateDate = this.timestampToTime(singleScript.updateDate);
            if("2"==singleScript.itemValue){
              this.machines[i].config.stroke="#00FF00";
            }else if("1"==singleScript.itemValue){
              this.machines[i].config.stroke="#FFD700";
            }else{
              this.machines[i].config.stroke="#2F4F4F";
            }
          } else if ("PLC_N" == singleScript.itemGrp) {
            this.machines[i].PLC_N.value = singleScript.itemValue;
            this.machines[i].PLC_N.oldVlue = singleScript.oldValue;
            this.machines[i].PLC_N.updateDate = this.timestampToTime(singleScript.updateDate);
            // 内卡控改变图形的颜色
            if("2"==singleScript.itemValue){
              this.machines[i].config.fill="#00FF00";
            }else if("1"==singleScript.itemValue){
              this.machines[i].config.fill="#FFD700";
            }else{
              this.machines[i].config.fill="#2F4F4F";
            }
          } else if ("AGV_CONT" == singleScript.itemGrp) {
            this.machines[i].AGV_CONT.value = singleScript.itemValue;
            this.machines[i].AGV_CONT.oldVlue = singleScript.oldValue;
            this.machines[i].AGV_CONT.updateDate = this.timestampToTime(singleScript.updateDate);
          } else if ("PLC_CONT" == singleScript.itemGrp) {
            this.machines[i].PLC_CONT.value = singleScript.itemValue;
            this.machines[i].PLC_CONT.oldVlue = singleScript.oldValue;
            this.machines[i].PLC_CONT.updateDate = this.timestampToTime(singleScript.updateDate);
          } else {

          }
        }
      }
    },
    /* 时间戳转换为时间 */
    timestampToTime(timestamp) {
      timestamp = timestamp ? timestamp : null;
      let date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
      let Y = date.getFullYear() + '-';
      let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
      let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
      let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
      let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },
    // 处理机台点击事件
    handleMachineClick(machine) {
      console.log("点击了机台:", machine.id);
      // this.hoveredMachine = machine;
      this.$nextTick(() => {
        this.$refs.monitorRef.init(machine);
      })
      // 根据电机的机台ITEM_CODE获取其所属的信号（如内外卡控、资料信息等）
      console.log('机台',machine.id,'外卡控:',machine.PLC_W.value,'内卡控',machine.PLC_N.value,'更新时间:',machine.AGV_W.updateDate)
      // const showMsg = this.texts.find(item => item.id === "ST_PIN");
      // showMsg.config.text = "站点：[" + machine.id + "];外卡控：<" + machine.AGV_W.value + ">;旧值：<" + machine.AGV_W.oldVlue + ">更新时间："+machine.AGV_W.updateDate;
    },
    handleDbClick(machine) {
      console.log("双击了机台:", machine.id);
      const modal = document.getElementById("modal");
      modal.style.display = "flex"; // 显示弹窗
    },
    handleEnter(machine){
      console.log("移入机台:", machine.id);
    }
  }
}
</script>

<style lang="scss">
.box-card {
  padding: 1 1px;
  font-size: 35px;
}

.itemData {
  margin-top: 5px;
  height: 50px;
  text-align: center;
  line-height: 50px;
  font-size: 30px;
  font-weight: bolder;
  background-color: dimgrey;
  color: aliceblue;
}

#zoom {
  margin-top: 20px;
  min-height: 500px;
}

.stackers {
  width: 100%;
  margin-top: 10px;
  font-size: 18px;
  font-family: cursive;

  strong {
    font-size: 16px;
  }

  .el-tag {
    font-weight: bold;
  }

  .el-card__body {
    padding-top: 10px;
    width: 100%;

    .card-col {
      // max-width: 100%;
      overflow-x: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .stacker-row {
    width: 100%;

    // display: flex;
    // justify-items:stretch;
    .el-col-12 {
      width: 49%;
    }

    .stacker-col {
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
      border: 1px solid #EBEEF5;
      border-radius: 5px;
      padding: 0 10px 10px;

      // background: red;
      .forks {
        margin-top: 10px;

        .fork-card {
          // background: dimgrey;
          // opacity: 0.5;
          // color: #fff;
          height: 290px;

          .fork-content {
            max-width: 96%;
            overflow-x: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .instruct {
            padding-left: 15px;

            // max-width: 96%;
            .ins-detail {
              margin-top: 5px;
              overflow-x: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;

              span {
                font-size: 16px;
              }

              strong {
                font-size: 14px;
              }
            }
          }

          .el-card__body {
            display: flex;
            flex-direction: column;
            align-items: center;
          }

          .card-col {
            margin: 10px 0;
          }

          .fork-title {
            margin: 0;
            text-align: center;
            font-weight: bold;
          }
        }
      }

      .stacker-status {
        background: #67C23A;
        text-align: center;
        margin: 0;
        padding: 10px 0 10px;
        border-bottom: 1px solid #EBEEF5;
        margin-bottom: 10px;
        font-size: 20px;
      }

      .top-status {
        .el-col {
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }
  }
}
</style>